﻿using MotionControl.Modules.LightSource;
using MotionControl.Services;
using MotionControl.Services.Interfaces;
using MotionControl.ViewModels;
using MotionControl.Views;
using Prism.Ioc;
using Prism.Modularity;
using System.Windows;
using MotionControl.Modules.PLC;
using MotionControl.Modules.RestService;
using System.Threading.Tasks;
using System;
using MotionControl.Core;
using NLog;
using MotionControl.Core.RegionAdapter;
using Prism.Regions;
using System.Windows.Controls;

namespace MotionControl
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        ILogger _logger;
        protected override Window CreateShell()
        {
            this.DispatcherUnhandledException += OnDispatcherUnhandledException;
            TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<IMessageService, MessageService>();
            containerRegistry.RegisterForNavigation<MainWindow, MainWindowViewModel>();

            _logger = LogManager.GetCurrentClassLogger();
            //注入到Prism DI容器中
            containerRegistry.RegisterInstance(_logger);
        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<RestServiceModule>();
            moduleCatalog.AddModule<PLCModule>();
            moduleCatalog.AddModule<LightSourceModule>();        
            base.ConfigureModuleCatalog(moduleCatalog);
        }

        /// <summary>
        /// 配置区域适配
        /// </summary>
        /// <param name="regionAdapterMappings"></param>
        protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
        {
            base.ConfigureRegionAdapterMappings(regionAdapterMappings);
            regionAdapterMappings.RegisterMapping(typeof(TabControl), Container.Resolve<TabRegionAdapter>());
        }


        private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            _logger.Fatal($"{e.Exception.StackTrace},{e.Exception.Message}");
        }

        private void OnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            _logger.Fatal($"{e.Exception.StackTrace},{e.Exception.Message}");
        }

        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            _logger.Fatal($"{ex.StackTrace},{ex.Message}");

            MiniDump.TryDump($"dumps\\MC_{DateTime.Now.ToString("HH-mm-ss-ms")}.dmp");
        }

    }
}
